<template>
  <div>
    <a-form
      :model="userData"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 12 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="用户名称"
        name="name"
        :rules="[{ required: true, message: '请输入用户的名称！' }]"
      >
        <a-input v-model:value="userData.name" placeholder="请输入用户名称" />
      </a-form-item>

      <a-form-item
        label="用户账号"
        name="userName"
        :rules="[{ required: true, message: '请输入用户账号！' }]"
      >
        <a-input
          placeholder="请输入用户账号"
          v-model:value="userData.userName"
        />
      </a-form-item>

      <a-form-item
        v-if="!userData.empId"
        label="用户密码"
        name="password"
        :rules="[{ required: true, message: '请输入用户密码！' }]"
      >
        <a-input-password
          placeholder="请输入密码"
          v-model:value="userData.password"
        />
      </a-form-item>
      <!-- 上传图片 -->
      <a-form-item name="avatar" label="用户头像">
        <Upload
          v-model="imagePath"
          action="http://localhost:8099/common/uploadOss"
          @submitImg="submitImg"
        />
      </a-form-item>

      <a-form-item label="用户性别" name="gender">
        <a-select
          ref="select"
          v-model:value="userData.gender"
          placeholder="请选择性别"
        >
          <a-select-option value="1">男</a-select-option>
          <a-select-option value="0">女</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="绑定社区"
        name="communityId"
        :rules="[{ required: true, message: '请绑定社区！' }]"
      >
        <a-select
          v-model:value="userData.communityId"
          show-search
          placeholder="请输入社区"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          :options="communityData"
          @search="handleSearch"
          @change="handleChange"
        ></a-select>
      </a-form-item>

      <a-form-item
        label="手机号"
        name="phone"
        :rules="[
          { required: true, message: '请输入联系号码！' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号!' },
        ]"
      >
        <a-input v-model:value.number="userData.phone" />
      </a-form-item>

      <a-form-item label="用户身份" name="type">
        <a-select
          ref="select"
          v-model:value="userData.type"
          placeholder="请选择身份"
        >
          <a-select-option :value="1">管理员</a-select-option>
          <a-select-option :value="2">用户</a-select-option>
          <a-select-option :value="3">社区医生</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        v-if="userData.type == 2"
        label="出生日期"
        name="birthDate"
        :rules="[{ required: true, message: '请输入出生日期！' }]"
      >
        <a-date-picker
          format="YYYY-MM-DD"
          valueFormat="YYYY-MM-DD"
          :disabledDate="disabledDate"
          style="width: 100%"
          v-model:value="userData.birthDate"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button
          style="margin-right: 20px; background-color: #b83b5e"
          type="primary"
          html-type="submit"
          >提交</a-button
        >
        <a-button @click="reset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import Upload from '@/common/Upload.vue'
import { deleteImage, deleteOssImage } from '@/api/config/api'
import { queryKey, apiAllList } from '@/api/Community/api'
import { apiAdd, apiQueryUser, apiUpdate } from '@/api/User/api'
import { EmployeeModel } from '@/api/User/model/loginModel'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
const communityData: any = ref([])

const props = defineProps(['empId'])
const emit = defineEmits(['receiveData'])
const imagePath = ref('')
const userData = ref<EmployeeModel>({
  empId: 0,
  name: '',
  userName: '',
  password: '',
  gender: '1',
  status: null,
  type: null,
  phone: '',
  avatar: '',
  communityId: null,
  birthDate: null,
  age: null,
})
let timeout: any = ref(null)
const currentValue: any = ref()
const submitImg = (url: any) => {
  let data: any = url
  userData.value.avatar = data.value.data
}
const disabledDate = (current: Dayjs) => {
  return current && current > dayjs().endOf('day')
}
const handleChange = (val: any) => {
  userData.value.communityId = val
}

const handleSearch = (val: any) => {
  fetch(val)
}
const fetch = (value: any) => {
  if (timeout.value) {
    clearTimeout(timeout.value)
    timeout.value = null
  }

  timeout.value = setTimeout(async () => {
    currentValue.value = value
    let res = await queryKey({
      communityName: value,
    })
    communityData.value = res.data.map((ele: any) => {
      return {
        label: ele.communityName,
        value: ele.communityId,
        ...ele,
      }
    })
  }, 300)
}
//重置表单数据
const reset = async () => {
  //判断图片路径是否为空
  if (userData.value.avatar != '') {
    await deleteOssImage({
      file: userData.value.avatar,
    })
    imagePath.value = ''
  }
  Object.keys(userData.value).forEach((key) => delete userData.value[key])
  userData.value.avatar = ''
}

//提交数据
const onFinish = async () => {
  if (userData.value.empId == 0) {
    try {
      await apiAdd(userData.value)
      Object.keys(userData.value).forEach((key) => delete userData.value[key])
      emit('receiveData', 3)
    } catch (error) {
      emit('receiveData', 4)
    }
  } else {
    try {
      await apiUpdate(userData.value)
      Object.keys(userData.value).forEach((key) => delete userData.value[key])
      emit('receiveData', 1)
    } catch (error) {
      emit('receiveData', 2)
    }
  }
}

const onFinishFailed = () => {
  message.error('请完善表单内容')
}

onMounted(async () => {
  if (props.empId != 0) {
    let res = await apiQueryUser(props.empId)
    userData.value = res.data
    console.log(userData.value)
    imagePath.value = userData.value.avatar
    let list = await apiAllList()
    communityData.value = list.data.map((ele: any) => {
      return {
        label: ele.communityName,
        value: ele.communityId,
        ...ele,
      }
    })
  }
})
</script>

<style lang="less" scoped></style>
